<template>
	<view class="chat">
		<!-- 顶部标题 -->
		<view class="topTabbar">
			<!-- 返回图标 -->
			<u-icon class="icon" name="arrow-left" size="20px" color="#000" @click="goback()"></u-icon>
			<!-- 标题 -->
			<view class="text">匿名</view>
		</view>
		<scroll-view :style="{height: `${windowHeight-inputHeight - 180}rpx`}" id="scrollview" scroll-y="true"
			:scroll-top="scrollTop" class="scroll-view">
			<!-- 聊天主体 -->
			<view id="msglistview" class="chat-body">
				<!-- 聊天记录 -->
				<view v-for="(item,index) in msgList" :key="index">
					<!-- 自己发的消息 -->
					<view class="">{{item.create_time}} </view>
					<view class="item self" v-if="userId == item.send_id">
						<!-- 文字内容 -->
						<view class="content right">
							{{item.context}}
						</view>
						<!-- 头像 -->
						<image class="avatar" :src="item.send_img">
						</image>
					</view>
					
					<!-- 机器人发的消息 -->
					<view class="item Ai" v-else>
						<!-- 头像 -->
						<image class="avatar" :src="item.send_img">
						</image>
						<!-- 文字内容 -->
						<view class="content left">
							{{item.context}}
						</view>
					</view>
				</view>
			</view>
		</scroll-view>
		<!-- 底部消息发送栏 -->
		<!-- 用来占位，防止聊天消息被发送框遮挡 -->
		<view class="chat-bottom" :style="{height: `${inputHeight}rpx`}">
			<view class="send-msg" :style="{bottom:`${keyboardHeight - 60}rpx`}">
				<view class="uni-textarea">
					<textarea v-model="chatMsg" maxlength="300" confirm-type="send" @confirm="handleSend"
						placeholder="快来聊天吧~" :show-confirm-bar="false" :adjust-position="false" @linechange="sendHeight"
						@focus="focus" @blur="blur" auto-height></textarea>
				</view>
				<button @click="handleSend" class="send-btn">发送</button>
			</view>
		</view>
	</view>
</template>
<script>
	import {
		getMsgList,
		sendMsg,
	} from '@/config/api.js';
	export default {
		data() {
			const userInfo = uni.getStorageSync('userInfo');
			return {
				queryList:{
					page:1,
					limit: 40,
				},
				userId: userInfo.id,
				//键盘高度
				keyboardHeight: 0,
				//底部消息发送高度
				bottomHeight: 0,
				//滚动距离
				scrollTop: 0,
				//发送的消息
				chatMsg: "",
				msgList: [{
						botContent: "你好啊，很高兴你可以关注我，请问我有什么可以帮助你的吗？",
						userContent: "",
						image: "/static/common/unname1.jpeg"
					},
					{
						botContent: "",
						userContent: "你好呀，非常高兴认识你",
						image: "/static/common/unname2.jpg"
					},
				]
			}
		},
		updated() {
			//页面更新时调用聊天消息定位到最底部
			this.scrollToBottom();
		},
		computed: {
			windowHeight() {
				return this.rpxTopx(uni.getSystemInfoSync().windowHeight)
			},
			// 键盘弹起来的高度+发送框高度
			inputHeight() {
				return this.bottomHeight + this.keyboardHeight
			}
		},
		onLoad(option) {
			this.queryList['toUserId'] = option.toUserId;
			this.getList(true);
			uni.onKeyboardHeightChange(res => {
				//这里正常来讲代码直接写
				//this.keyboardHeight=this.rpxTopx(res.height)就行了
				//但是之前界面ui设计聊天框的高度有点高,为了不让键盘和聊天输入框之间距离差太大所以我改动了一下。
				this.keyboardHeight = this.rpxTopx(res.height)
				if (this.keyboardHeight < 0) this.keyboardHeight = 0;
			})
		},
		onUnload() {
			// uni.offKeyboardHeightChange()
		},
		methods: {
			getList(isInit){
				this.queryList['init'] = null;
				if(isInit)this.queryList['init'] = 1;
				getMsgList(this.queryList).then(res => {
					this.msgList = res.data.reverse();
				})
			},
			goback() {
				console.log('123'); // 确认方法被调用
				const pages = getCurrentPages();
				console.log(pages); // 查看页面堆栈

				// 确保有页面可以返回
				if (pages.length > 1) {
					wx.navigateBack({
						delta: 1 // 返回上一层
					});
				} else {
					// 在没有可返回页面时，可以导航到主页
					wx.reLaunch({
						url: '/pages/home/home' // 替换为您的首页路径
					});
					// 或者关闭当前页面
					wx.navigateBack({
						delta: 1 // 关闭当前页面
					});
				}
			},

			focus() {
				this.scrollToBottom()
			},
			blur() {
				this.scrollToBottom()
			},
			// px转换成rpx
			rpxTopx(px) {
				let deviceWidth = uni.getSystemInfoSync().windowWidth
				let rpx = (750 / deviceWidth) * Number(px)
				return Math.floor(rpx)
			},
			// 监视聊天发送栏高度
			sendHeight() {
				setTimeout(() => {
					let query = uni.createSelectorQuery();
					query.select('.send-msg').boundingClientRect()
					query.exec(res => {
						this.bottomHeight = this.rpxTopx(res[0].height)
					})
				}, 10)
			},
			// 滚动至聊天底部
			scrollToBottom(e) {
				setTimeout(() => {
					let query = uni.createSelectorQuery().in(this);
					query.select('#scrollview').boundingClientRect();
					query.select('#msglistview').boundingClientRect();
					query.exec((res) => {
						if (res[1].height > res[0].height) {
							this.scrollTop = this.rpxTopx(res[1].height - res[0].height)
						}
					})
				}, 15)
			},
			// 发送消息
			handleSend() {
				//如果消息不为空
				if (!this.chatMsg || !/^\s+$/.test(this.chatMsg)) {
					// let obj = {
					// 	botContent: "",
					// 	userContent: this.chatMsg,
					// 	image: "/static/common/unname2.jpg"
					// }
					// this.msgList.push(obj);
					// this.chatMsg = '';
					
					sendMsg({
						toUserId: this.queryList.toUserId,
						context: this.chatMsg
					}).then(res => {
						this.chatMsg = '';
						this.getList();
						this.scrollToBottom()
					})
					
				} else {
					this.$modal.showToast('不能发送空白消息')
				}
			},
		}
	}
</script>
<style lang="scss" scoped>
	@import 'DiscountsActivity.scss';
</style>